﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using Worktool.CODE_Chris.DataSourceHelpers;
using Worktool.CODE_Chris.SQL_DATA;

namespace Worktool
{
    public partial class Baufortschritt : Form
    {
        private SQL sql;
        private Boolean isInit = true;
        private BaufortschrittHelper helper;
        private String[,] areas;
        
        public Baufortschritt()
        {
            InitializeComponent();
            init();
        }

        private void init()
        {
            sql = new SQL();
            helper = new BaufortschrittHelper(dataGridView1, dataGridView2, this);

            areas = sql.receiveSQL("SELECT [ID],[Venue],[Venue ID MW],[Venue ID ASC] FROM STAMMDATEN_areas");

            fillTablesInit();

            isInit = false;
        }

        #region Init
        private void fillTablesInit()
        {
            try
            {
                helper.getData1();
                helper.getData2();
            }
            catch (Exception e)
            {

            }
        }

        private void Baufortschritt_Load(object sender, EventArgs e)
        {
            this.Text = "Baufortschritt: " + Login.currentDBName; 

            typeof(DataGridView).InvokeMember("DoubleBuffered", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty, null, dataGridView1, new object[] { true });
            typeof(DataGridView).InvokeMember("DoubleBuffered", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty, null, dataGridView2, new object[] { true });
        }
        #endregion

        #region Filter
        //
        // Alle Kabel aus dem Bereich anzeigen
        //
        private void button1_Click(object sender, EventArgs e)
        {
            string venueIdent = "ABCDE";
            List<string> posList = new List<string> { };
            string retValue = "";
            string venue = "";
            int reihen = 0;
                
            if (textBox1.Text != "")
            {
                
                if (dataGridView1.RowCount > 0)
                {
                    //Die richtige Venue ID aus der ersten Zelle auslesen                
                    venue = dataGridView1.Rows[0].Cells["Venue"].Value.ToString();

                    for (int a = 0; a < areas.GetLength(1); a++)
                    {
                        if (areas[1, a] == "")
                        {
                            venueIdent = areas[2, a];
                            break;
                        }
                    }
                }

                for (int a = 0; a < dataGridView1.RowCount; a++)
                {

                    if (dataGridView1.Rows[a].Cells["Positions_ID"].Value.ToString() != "")
                    {
                        posList.Add(dataGridView1.Rows[a].Cells["Positions_ID"].Value.ToString());
                    }

                }

                try
                {
                    retValue = "'" + String.Join("','", posList) + "'";
                    if (helper.getTable2() != null) helper.getTable2().DefaultView.RowFilter = string.Format("(CableFrom2 IN (" + retValue + ") OR (ISNULL(CableFrom2,'') = '' AND Cableto2 IN (" + retValue + "))) OR (Cableto2 IN (" + retValue + ") OR (ISNULL(Cableto2,'') = '' AND CableFrom2 IN (" + retValue + ")))");
                }
                catch (Exception ex)
                { } 
            }
        }

        //
        // Nur die Non-Rack-Label aus dem Bereich anzeigen
        //
        private void button2_Click(object sender, EventArgs e)
        {
            List<string> posList = new List<string> { };
            string retValue = "";
            if (textBox1.Text != "")
            {
                for (int a = 0; a < dataGridView1.RowCount; a++)
                {

                    try
                    {

                        if (dataGridView1.Rows[a].Cells["Positions_ID"].Value.ToString().Length > 4)
                        {
                            String subString = dataGridView1.Rows[a].Cells["Positions_ID"].Value.ToString().Substring(0, 4);
                            if (subString != "ENSR" && subString != "ENLR" && subString != "ENVR" && subString != "ELRR")
                            {
                                posList.Add(dataGridView1.Rows[a].Cells["Positions_ID"].Value.ToString());
                            } 
                        }
                    }
                    catch (Exception ex)
                    {
 
                    }
                }

                try
                {
                    retValue = "'" + String.Join("','", posList)  + "'";
                    if (helper.getTable2() != null) helper.getTable2().DefaultView.RowFilter = string.Format("((CableFrom2 IN (" + retValue + ") OR ISNULL(CableFrom2,'') = '') AND Cableto2 IN (" + retValue + ")) OR ((Cableto2 IN (" + retValue + ") OR ISNULL(Cableto2,'') = '') AND CableFrom2 IN (" + retValue + "))");                    
                }
                catch (Exception ex)
                {
 
                } 
            }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            if (helper.getTable1() != null) helper.getTable1().DefaultView.RowFilter = string.Format("Venue LIKE '{0}' AND Manufacturer LIKE '{1}' AND Model LIKE '{2}' AND ISNULL(JLM,'') LIKE '{3}' AND ISNULL(Positions_ID,'')  LIKE '{4}' ", (textBox1.Text + "*"), (textBox2.Text + "*"), (textBox3.Text + "*"), (textBox4.Text + "*"), (textBox5.Text + "*"));
        }
        #endregion

        #region Export
        //
        // Export to Excel
        //
        private void button4_Click(object sender, EventArgs e)
        {

            string pfad = System.Windows.Forms.Application.StartupPath.ToString();
            dataGridView2.SelectAll();
            DataObject dataObj = dataGridView2.GetClipboardContent();
            if (dataObj != null)
                Clipboard.SetDataObject(dataObj);
            Microsoft.Office.Interop.Excel.Application xlexcel;
            Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
            Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
            xlexcel = new Microsoft.Office.Interop.Excel.Application();
            try
            {
                SaveFileDialog saveFile = new SaveFileDialog();

                saveFile.Filter = "Excel-Format (*.xlsx)|*.xlsx";
                saveFile.FilterIndex = 2;
                saveFile.RestoreDirectory = true;

                if (saveFile.ShowDialog() == DialogResult.OK)
                {
                    File.Copy(Path.Combine(Login.dictSettings["netzwerkordner"], "Templates\\" + Login.currentDBName + "\\Installation\\InstStatus\\TemplateCablelist.xlsx"), saveFile.FileName, true);

                    xlWorkBook = xlexcel.Workbooks.Open(saveFile.FileName);
                    xlexcel.Visible = true;
                    xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
                    xlWorkSheet.Cells[1, 8] = dataGridView1.Rows[0].Cells["Venue"].Value.ToString();
                    Microsoft.Office.Interop.Excel.Range CR = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[3, 2];
                    CR.Select();
                    xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
                    xlWorkSheet.Cells.Replace("TRUE", "X");
                    xlWorkSheet.Cells.Replace("FALSE", "");
                }


            }
            catch (ArgumentOutOfRangeException exx)
            {

            }
            catch (Exception ex)
            {
                MessageBox.Show("Konnte Vorlage für Kabelliste nicht finden.\r\n\r\nPfad, in dem die Datei erwartet wird:\r\n" + Path.Combine(Login.dictSettings["netzwerkordner"], "Templates\\" + Login.currentDBName + "\\Installation\\InstStatus\\TemplateCablelist.xlsx"));
            }
            dataGridView1.ClearSelection();
        }
        #endregion

        #region Daten neu laden
        public void reloadAllData()
        {
            Cursor.Current = Cursors.WaitCursor;
            this.Enabled = false;
            fillTablesInit();
            textBox1_TextChanged(null, null);
            this.Enabled = true;
            Cursor.Current = Cursors.Default;
        }
        #endregion

    }
}
